<?php
namespace Home\Service;

class OrderService
{
    public function createRed($red_id)
    {
        $red = M('red_bag')->field('user_id,money,service_charge')->find($red_id);

        // 订单总费用
        $total_money = $red['money'] + $red['service_charge'];

        // 余额优先支付
        $user_money = M('user')->where(['id' => $red['user_id']])->getField('money');

        $balance_pay_money = $user_money > $total_money ? $total_money : $user_money;
        $wx_pay_money      = $total_money - $balance_pay_money;

        // 创建订单
        $order = [
            'order_no'      => $order_no = generate_red_order_no($red['user_id']),
            'red_id'        => $red_id,
            'user_id'       => $red['user_id'],
            'total'         => $total_money,
            'balance_money' => $balance_pay_money,
            'wx_money'      => $wx_pay_money,
            'add_time'      => CUR_DATETIME,
        ];

        // 余额够支付
        if ($wx_pay_money == 0) {
            $order['is_pay']   = 1;
            $order['pay_time'] = CUR_DATETIME;
            $result            = D('user', 'Service')->moneyLog($order['user_id'], -$balance_pay_money, '支付红包');

            M('red_bag')->where(['id' => $red_id])->save(['status' => 2]);
        } else {
            $order['is_pay'] = 0;
        }

        begin();
        $id = M('red_order')->add($order);

        if ($id) {
            commit();
            return $order_no;
        } else {
            rollback();
            return false;
        }
    }

    public function payRed($order_no, $transaction_id = '', $wx_money = 0.00)
    {
        $order = M('red_order')->field('user_id,total')->where(['order_no' => $order_no])->find();
        if (!$order) {
            return false;
        }
        $total = $order['total'];

        // 余额支付
        $user_money = M('user')->where(['id' => $order['user_id']])->getField('money');
        // 余额+微信支付 不足支付
        if ($user_money + $wx_money < $total) {
            return false;
        }

        $balance_pay_money = $user_money > $total ? $total : $user_money;
        $wx_pay_money      = $wx_money;

        if ($balance_pay_money + $wx_pay_money != $total) {
            return false;
        }

    }
}
